let sha1 = require('sha1');
let rawBody = require('raw-body');
let Wechat = require('./wechat');
let util = require('../libs/util');
module.exports = function (opt,handler) {
    let wechat = new Wechat(opt);
    return function* (next) {
        let token = opt.token;
        let timestamp = this.query.timestamp;
        let nonce = this.query.nonce;
        let signature = this.query.signature;
        let echostr = this.query.echostr;
        let arrStr = [token, timestamp, nonce].sort().join('');
        let sha = sha1(arrStr);
        if (this.method === 'GET') {  //微信验证签名接口用的是get的方式
            if (sha == signature) {
                console.log(11111111111)
                this.body = echostr; 
            } else {
                console.log('签名错误，不是来自微信的get请求')
            }
        }else if(this.method === 'POST') {  //用户在微信操作事件（点击菜单按钮、发送消息），或者普通接口发送
            if (sha == signature) {  //签名一直说明是冲微信发送过来的post
                let data = yield rawBody(this.req,{   //data为数据流
                    length: this.length,
                    limit: '1mb',
                    encoding: this.charset
                })
                let content = yield util.parseXMLAsync(data);
                let message = util.formatMassege(content.xml);
                console.log(message);
                this.weixin = message;
                yield handler.call(this,next);
                wechat.reply.call(this);
            } else { //者普通接口发送
                console.log('不是来自微信的请求')
            }
        }


    }
}